<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./10.style.css">
</head>
<body>
    <div id="app">
        <header>
            <section>编号</section>
            <section>名称</section>
            <section>单价</section>
            <section>数量</section>
            <section>总价</section>
        </header>
        <section v-for="(item,index) in products" :key="item.id">
            <span>{{item.id}}</span>&nbsp;&nbsp;
            <span>{{item.name}}</span>&nbsp;&nbsp;
            <span>{{item.price}}</span>&nbsp;&nbsp;
            
            <button @click="addClick(index)">+</button>&nbsp;&nbsp;
            <span>{{item.count}}</span>&nbsp;&nbsp;
            <button @click="subClick(index)">-</button>&nbsp;&nbsp;
            
            <span>{{item.price*item.count}}</span>
        </section>
        <h2>总价：{{totalPrice}}</h2>
    </div>
    <script src="./node_modules/vue/dist/vue.js"></script>
    <script>
    // 用组件的方法实现点击加或减按钮时数量、加减、总计也随之加减
        let vm=new Vue({
            el:"#app",
            data:{
                products:[
                    {
                        id:1,
                        name:"apple",
                        price:3,
                        count:2,
                    },
                    {
                        id:2,
                        name:"pear",
                        price:4,
                        count:3,
                    },
                    {
                        id:3,
                        name:"banana",
                        price:5,
                        count:4,
                    },
                ]
            },
            // 计算属性   总价是实时改变的，需要用计算属性来获得
            computed:{
                /* 计算属性 特点：
                        1、具有缓存的作用
                        2、实时计算的
                */
                totalPrice:function(){
                    let totalPrice=0;
                    this.products.map(v=>{
                        totalPrice+=v.price*v.count
                    });
                    return totalPrice;
                }
            },
            methods:{
                addClick:function(index){
                    // 更新数据 用JSON转换
                    let newProducts=JSON.parse(JSON.stringify(this.products));
                    newProducts[index].count+=1;
                    this.products=newProducts;
                },
                subClick:function(index){
                    // 更新数据 用JSON转换
                    let newProducts=JSON.parse(JSON.stringify(this.products));
                    newProducts[index].count-=1;
                    this.products=newProducts;
                }
            }


        })







    </script>
</body>
</html>